import { login, getUserInfo, register } from '@/api/sys'
import md5 from 'md5'
import { setItem, getItem, removeAllItems } from '@/utils/storage'
import { TOKEN, INFO, ROLES, USERTYPE } from '@/const/index'
import router from '@/router'
import { setTimeStamp } from '@/utils/auth'
export default {
  namespaced: true,
  state: () => ({
    token: getItem(TOKEN) || '',
    userInfo: getItem(INFO) || {},
    roles: getItem(ROLES) || [],
    userType: getItem(USERTYPE) || ''
  }),
  mutations: {
    setToken (state, token) {
      state.token = token
      setItem(TOKEN, token)
    },
    setUserInfo (state, userInfo) {
      state.userInfo = userInfo
      setItem(INFO, userInfo)
    },
    setUserRoles (state, roles) {
      state.roles = roles
      setItem(ROLES, roles)
    },
    setUserType (state, userType) {
      state.userType = userType
      setItem(USERTYPE, userType)
    }
  },
  actions: {
    /**
     * 登录请求动作
     * @param {*} context
     * @param {*} userInfo
     * @returns
     */
    login (context, userInfo) {
      const { userName, password, code } = userInfo
      return new Promise((resolve, reject) => {
        login({
          userName,
          password: md5(password),
          code: code || '54188'
        }).then(data => {
          // this.commit方法
          this.commit('user/setToken', data.token)
          // 后端已经封装成数组对象，不需要前端再做处理
          this.commit('user/setRoles', data.rules || [])

          this.commit('user/setUserType', data.userType)
          // 跳转
          router.push('/')
          // 保存登录时间
          setTimeStamp()
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    },
    /**
     * 获取用户信息
     * @param {*} context
     */
    async getUserInfo (context) {
      const res = await getUserInfo()
      this.commit('user/setUserInfo', res)
      return res
    },
    logout () {
      this.commit('user/setToken', '')
      this.commit('user/setUserInfo', {})
      removeAllItems()
      this.commit('user/setRoles', [])
      this.commit('user/setUserType', '')
      router.push('/login')
    },
    async register (context, user) {
      const res = await register(user)
      if (res.token) {
        this.commit('user/setToken', res.token)
        this.commit('user/setUserType', res.userType)
        if (res.userType) {
          router.push('/applicant/userinfo')
        } else {
          router.push('/')
        }
      }
      return res
    }
  }
}
